﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyLocalChurch.Constants;
using MyLocalChurch.Models;
using MyLocalChurch.Models.Enumerations;
using MyLocalChurch.Models.KidsChurch;
using RKConsulting.Helpers;
using RKConsulting.Web.Helpers;

namespace MyLocalChurch.Business
{
    public static class GuardianManager
    {
        public static Guardian GetGuardianAndUpdateCache(MyContext context, string barcode)
        {
            if (string.IsNullOrEmpty(barcode))
                return null;

            var guardian = CacheHelper.Get<Guardian>(CacheKeys.Guardian);
            if (guardian != null)
            {
                var validBarcode = BarcodeManager.GetValidBarcode(guardian.Barcodes);
                if (validBarcode != null && validBarcode.Code == barcode)
                    return guardian;

                guardian = null;
            }

            var guardians = context.Guardians.ToList();
            foreach (var g in guardians)
            {
                var validBarcode = BarcodeManager.GetValidBarcode(g.Barcodes);
                
                if (validBarcode == null || validBarcode.Code != barcode)
                    continue;

                guardian = g;
                break;
            }

            if (guardian == null)
                CacheHelper.Remove(CacheKeys.Guardian);
            else
                CacheHelper.Add(CacheKeys.Guardian, guardian);

            return guardian;
        }

        public static Guardian GetGuardianAndUpdateCache(MyContext context, int? guardianId)
        {
            if (!guardianId.HasValue)
                return null;

            var guardian = CacheHelper.Get<Guardian>(CacheKeys.Guardian);
            if (guardian != null && guardian.Id == guardianId.Value)
                return guardian;

            var id = guardianId.GetValueOrDefault();
            guardian = context.Guardians.FirstOrDefault(g => g.Id == id);

            if (guardian == null)
                CacheHelper.Remove(CacheKeys.Guardian);
            else
                CacheHelper.Add(CacheKeys.Guardian, guardian);

            return guardian;
        }
    }
}